<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>城市温度分析 - 科技感高对比度版</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>

    <!-- 全局颜色变量 -->
    <style>
        :root {
            --primary: #00FFFF;       /* 主色 - 霓虹蓝 */
            --secondary: #00FF7F;     /* 辅助色 - 全息绿 */
            --dark-bg: #0F172A;       /* 深色背景 */
            --light-text: #FFFFFF;    /* 浅色文字 */
            --medium-text: #A8C7FF;   /* 中色文字 */
            --accent: #FF5722;        /* 强调色 - 橙红 */
            --card-bg: rgba(15, 23, 42, 0.7); /* 卡片背景 */
            --card-border: rgba(0, 255, 255, 0.2); /* 卡片边框 */
        }
    </style>

    <!-- 配置Tailwind自定义主题 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: 'var(--primary)',
                        secondary: 'var(--secondary)',
                        accent: 'var(--accent)',
                        dark: 'var(--dark-bg)',
                        light: 'var(--light-text)',
                        medium: 'var(--medium-text)',
                        card: {
                            bg: 'var(--card-bg)',
                            border: 'var(--card-border)'
                        },
                        success: '#52C41A',
                        warning: '#FAAD14',
                        danger: '#FF4D4F',
                        neutral: {
                            100: '#F5F7FA',
                            200: '#E4E7ED',
                            300: '#DCDFE6',
                            400: '#C0C4CC',
                            500: '#909399',
                            600: '#606266',
                            700: '#303133',
                            800: 'var(--dark-bg)',
                        }
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 4px 20px rgba(0, 255, 255, 0.1)',
                        'card-hover': '0 8px 30px rgba(0, 255, 255, 0.2)',
                        'neon': '0 0 10px rgba(0, 255, 255, 0.5), 0 0 20px rgba(0, 255, 255, 0.3)',
                    }
                }
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .glass-effect {
                backdrop-filter: blur(8px);
            }
            .card-animate {
                transition: all 0.3s ease;
            }
            .card-animate:hover {
                transform: translateY(-5px);
                box-shadow: 0 8px 30px rgba(0, 255, 255, 0.2);
            }
            .text-neon {
                text-shadow: 0 0 10px rgba(0, 255, 255, 0.5);
            }
            .neon-border {
                border: 1px solid rgba(0, 255, 255, 0.2);
            }
        }
    </style>
</head>
<body class="font-inter bg-neutral-800 text-light min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-card-bg neon-border shadow-sm sticky top-0 z-50 transition-all duration-300 glass-effect" id="mainHeader">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-thermometer-half text-primary text-2xl text-neon"></i>
                <h1 class="text-xl font-bold text-light">城市温度分析</h1>
            </div>

            <!-- 返回首页功能 -->
            <div class="flex items-center space-x-4">
                <div class="text-sm text-medium">
                    <span id="currentDate">加载中...</span>
                </div>
                <a href="/" class="text-primary hover:text-secondary transition-colors flex items-center space-x-1 group">
                    <i class="fa fa-home text-lg group-hover:scale-110 transition-transform"></i>
                    <span class="hidden md:block">返回首页</span>
                </a>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 py-8 max-w-6xl">
        <!-- 过滤器容器 -->
        <div class="bg-card-bg neon-border rounded-xl shadow-card p-6 mb-8 transform transition-all duration-300 hover:shadow-card-hover">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                    <label for="citySelect" class="block text-sm font-medium text-medium mb-2">选择城市</label>
                    <div class="relative">
                        <select id="citySelect" class="w-full bg-neutral-700 border border-card-border rounded-lg py-3 px-4 pr-8 appearance-none focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all text-light">
                            {% for city in cities %}
                                <option value="{{ city }}" {% if loop.first %}selected{% endif %}>{{ city }}</option>
                            {% endfor %}
                        </select>
                        <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-medium">
                            <i class="fa fa-chevron-down text-xs"></i>
                        </div>
                    </div>
                </div>

                <div>
                    <label for="yearSelect" class="block text-sm font-medium text-medium mb-2">选择年份</label>
                    <div class="relative">
                        <select id="yearSelect" class="w-full bg-neutral-700 border border-card-border rounded-lg py-3 px-4 pr-8 appearance-none focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all text-light">
                            <option value="">全部年份</option>
                            {% for year in years %}
                                <option value="{{ year }}">{{ year }}</option>
                            {% endfor %}
                        </select>
                        <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-medium">
                            <i class="fa fa-chevron-down text-xs"></i>
                        </div>
                    </div>
                </div>

                <div>
                    <label for="tempTypeSelect" class="block text-sm font-medium text-medium mb-2">温度类型</label>
                    <div class="relative">
                        <select id="tempTypeSelect" class="w-full bg-neutral-700 border border-card-border rounded-lg py-3 px-4 pr-8 appearance-none focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all text-light">
                            <option value="max">最高温度</option>
                            <option value="min">最低温度</option>
                            <option value="both">最高/最低温度</option>
                        </select>
                        <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-medium">
                            <i class="fa fa-chevron-down text-xs"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表容器 -->
        <div class="bg-card-bg neon-border rounded-xl shadow-card p-6 mb-8 transform transition-all duration-300 hover:shadow-card-hover">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-bold text-light">温度趋势分析</h2>
                <div class="flex space-x-2">
                    <button id="chartZoomIn" class="p-2 rounded-lg bg-neutral-700 hover:bg-primary/20 transition-colors text-light">
                        <i class="fa fa-search-plus"></i>
                    </button>
                    <button id="chartZoomOut" class="p-2 rounded-lg bg-neutral-700 hover:bg-primary/20 transition-colors text-light">
                        <i class="fa fa-search-minus"></i>
                    </button>
                    <button id="chartRefresh" class="p-2 rounded-lg bg-neutral-700 hover:bg-primary/20 transition-colors text-light">
                        <i class="fa fa-refresh"></i>
                    </button>
                </div>
            </div>

            <div class="relative">
                <div id="chartLoading" class="absolute inset-0 bg-neutral-800/80 flex items-center justify-center z-10">
                    <div class="text-center">
                        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-2"></div>
                        <p class="text-medium">数据加载中...</p>
                    </div>
                </div>
                <div id="chart-container" style="width: 100%; height: 600px;"></div>
            </div>
        </div>

        <!-- 数据概览卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="bg-card-bg neon-border rounded-xl shadow-card p-6 transform transition-all duration-300 hover:shadow-card-hover hover:scale-[1.02]">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <p class="text-sm text-medium">当前分析</p>
                        <h3 class="text-2xl font-bold text-light mt-1" id="currentAnalysis">加载中...</h3>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                        <i class="fa fa-bar-chart text-primary"></i>
                    </div>
                </div>
                <div class="text-sm text-medium">
                    <span class="flex items-center"><i class="fa fa-calendar-o mr-2"></i><span id="analysisRange">数据范围: 加载中...</span></span>
                </div>
            </div>

            <div class="bg-card-bg neon-border rounded-xl shadow-card p-6 transform transition-all duration-300 hover:shadow-card-hover hover:scale-[1.02]">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <p class="text-sm text-medium">最高温度</p>
                        <h3 class="text-2xl font-bold text-light mt-1" id="maxTemperature">加载中...</h3>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-accent/10 flex items-center justify-center">
                        <i class="fa fa-thermometer-full text-accent"></i>
                    </div>
                </div>
                <div class="text-sm text-medium">
                    <span class="flex items-center"><i class="fa fa-calendar-check-o mr-2"></i><span id="maxTempDate">日期: 加载中...</span></span>
                </div>
            </div>

            <div class="bg-card-bg neon-border rounded-xl shadow-card p-6 transform transition-all duration-300 hover:shadow-card-hover hover:scale-[1.02]">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <p class="text-sm text-medium">最低温度</p>
                        <h3 class="text-2xl font-bold text-light mt-1" id="minTemperature">加载中...</h3>
                    </div>
                    <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center">
                        <i class="fa fa-thermometer-empty text-secondary"></i>
                    </div>
                </div>
                <div class="text-sm text-medium">
                    <span class="flex items-center"><i class="fa fa-calendar-check-o mr-2"></i><span id="minTempDate">日期: 加载中...</span></span>
                </div>
            </div>
        </div>
    </main>

    <footer class="bg-card-bg neon-border border-t border-card-border mt-12">
        <div class="container mx-auto px-4 py-8">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <p class="text-sm text-medium">© 2025 城市温度分析系统 | 数据仅供参考</p>
                </div>
                <div class="flex space-x-4">
                    <a href="#" class="text-medium hover:text-primary transition-colors">
                        <i class="fa fa-question-circle"></i> 帮助中心
                    </a>
                    <a href="#" class="text-medium hover:text-primary transition-colors">
                        <i class="fa fa-info-circle"></i> 关于我们
                    </a>
                    <a href="#" class="text-medium hover:text-primary transition-colors">
                        <i class="fa fa-envelope-o"></i> 联系我们
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <script>
        // 初始化图表
        const chartDom = document.getElementById('chart-container');
        const myChart = echarts.init(chartDom);

        // 基础图表配置
        const baseOption = {
            backgroundColor: 'transparent',
            grid: { left: '3%', right: '4%', bottom: '8%', containLabel: true },
            xAxis: {
                type: 'category',
                axisLine: { lineStyle: { color: '#00FFFF', width: 2 } },
                axisLabel: {
                    color: '#A8C7FF',
                    fontSize: 14,
                    interval: 0,
                    formatter: function (value) {
                        const [year, month] = value.split('-');
                        return `${year}年${month}月`;
                    }
                },
                categoryGap: '10%',
            },
            yAxis: {
                type: 'value',
                axisLine: { lineStyle: { color: '#00FFFF', width: 2 } },
                splitLine: { lineStyle: { color: 'rgba(0, 255, 255, 0.1)' } },
                axisLabel: {
                    formatter: '{value}℃',
                    color: '#A8C7FF',
                    fontSize: 14
                }
            },
            tooltip: {
                trigger: 'axis',
                backgroundColor: 'rgba(15, 23, 42, 0.9)',
                borderColor: 'rgba(0, 255, 255, 0.3)',
                borderWidth: 1,
                padding: 12,
                textStyle: {
                    color: '#FFFFFF',
                    fontFamily: 'Inter, sans-serif'
                },
                formatter: function (params) {
                    const date = params[0].name;
                    const values = params.map(item => `${item.seriesName}: ${item.value}℃`).join('<br>');
                    return `<strong>${date}</strong><br>${values}`;
                }
            },
            legend: {
                data: ['最高温度', '最低温度'],
                textStyle: { color: '#A8C7FF' },
                bottom: '2%'
            }
        };

        // 重置图表
        function reset() {
            myChart.clear();
            myChart.setOption(baseOption);
        }

        // 更新图表
        function updateChart() {
            reset();

            const city = document.getElementById('citySelect').value;
            const year = document.getElementById('yearSelect').value;
            const tempType = document.getElementById('tempTypeSelect').value;

            if (!city) return;

            const requests = [];

            if (tempType === 'max' || tempType === 'both') {
                requests.push(
                    fetch(`/monthly_high_temperature?urban=${encodeURIComponent(city)}${year ? `&year=${year}` : ''}`)
                        .then(response => {
                            if (!response.ok) throw new Error(`最高温度请求失败：${response.status}`);
                            return response.json();
                        })
                );
            }
            if (tempType === 'min' || tempType === 'both') {
                requests.push(
                    fetch(`/monthly_low_temperature?urban=${encodeURIComponent(city)}${year ? `&year=${year}` : ''}`)
                        .then(response => {
                            if (!response.ok) throw new Error(`最低温度请求失败：${response.status}`);
                            return response.json();
                        })
                );
            }

            myChart.showLoading({
                text: '数据加载中...',
                color: '#00FFFF',
                textColor: '#FFFFFF',
                maskColor: 'rgba(15, 23, 42, 0.7)',
                fontSize: 16
            });

            Promise.all(requests)
                .then(dataList => {
                    myChart.hideLoading();

                    let highData = null;
                    let lowData = null;

                    if (tempType === 'both') {
                        [highData, lowData] = dataList;
                    } else if (tempType === 'max') {
                        [highData] = dataList;
                    } else if (tempType === 'min') {
                        [lowData] = dataList;
                    }

                    const series = [];

                    const xData = (highData?.months || lowData?.months || []).map(m => {
                        const [yearPart, monthPart] = m.split('-');
                        return `${yearPart}-${monthPart}`;
                    });

                    if (highData && highData.high_temps) {
                        series.push({
                            name: '最高温度',
                            type: 'bar',
                            data: highData.high_temps,
                            barWidth: '25%',
                            itemStyle: { color: '#FF5722' },
                            label: {
                                show: true,
                                position: 'top',
                                color: '#FFFFFF',
                                fontSize: 12,
                                formatter: '{c}℃'
                            }
                        });
                    }

                    if (lowData && lowData.low_temps) {
                        series.push({
                            name: '最低温度',
                            type: 'bar',
                            data: lowData.low_temps,
                            barWidth: '25%',
                            itemStyle: { color: '#00FF7F' },
                            label: {
                                show: true,
                                position: 'bottom',
                                color: '#FFFFFF',
                                fontSize: 12,
                                formatter: '{c}℃'
                            }
                        });
                    }

                    if (xData.length === 0) {
                        throw new Error('没有找到匹配的温度数据');
                    }

                    // 更新数据概览卡片
                    updateSummaryCards(highData, lowData, city, year);

                    // 设置图表选项
                    myChart.setOption({
                        xAxis: { data: xData },
                        legend: { data: series.map(s => s.name) },
                        series: series
                    });
                })
                .catch(error => {
                    myChart.hideLoading();
                    console.error('数据加载错误:', error);
                    alert(`数据加载失败: ${error.message}`);
                });
        }

        // 更新数据概览卡片
        function updateSummaryCards(highData, lowData, city, year) {
            // 更新当前分析
            let analysisText = `${city}市温度分析`;
            if (year) {
                analysisText += ` (${year}年)`;
            }
            document.getElementById('currentAnalysis').textContent = analysisText;

            // 更新分析范围
            let rangeText = '全部时间';
            if (highData && highData.months && highData.months.length > 0) {
                const firstMonth = highData.months[0];
                const lastMonth = highData.months[highData.months.length - 1];
                rangeText = `${firstMonth}至${lastMonth}`;
            }
            document.getElementById('analysisRange').textContent = `数据范围: ${rangeText}`;

            // 更新最高温度
            if (highData && highData.high_temps && highData.high_temps.length > 0) {
                const maxTemp = Math.max(...highData.high_temps);
                const maxTempIndex = highData.high_temps.indexOf(maxTemp);
                const maxTempDate = highData.months[maxTempIndex];
                document.getElementById('maxTemperature').textContent = `${maxTemp}℃`;
                document.getElementById('maxTempDate').textContent = `日期: ${maxTempDate}`;
            }

            // 更新最低温度
            if (lowData && lowData.low_temps && lowData.low_temps.length > 0) {
                const minTemp = Math.min(...lowData.low_temps);
                const minTempIndex = lowData.low_temps.indexOf(minTemp);
                const minTempDate = lowData.months[minTempIndex];
                document.getElementById('minTemperature').textContent = `${minTemp}℃`;
                document.getElementById('minTempDate').textContent = `日期: ${minTempDate}`;
            }
        }

        // 初始化页面
        document.addEventListener('DOMContentLoaded', () => {
            // 设置当前日期
            document.getElementById('currentDate').textContent = new Date().toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                weekday: 'long'
            });

            // 初始化图表
            updateChart();

            // 添加事件监听器
            ['citySelect', 'yearSelect', 'tempTypeSelect'].forEach(id => {
                document.getElementById(id).addEventListener('change', updateChart);
            });

            // 图表交互按钮
            document.getElementById('chartZoomIn').addEventListener('click', () => {
                myChart.dispatchAction({
                    type: 'dataZoom',
                    zoom: 1.1
                });
            });

            document.getElementById('chartZoomOut').addEventListener('click', () => {
                myChart.dispatchAction({
                    type: 'dataZoom',
                    zoom: 0.9
                });
            });

            document.getElementById('chartRefresh').addEventListener('click', () => {
                document.getElementById('chartLoading').style.display = 'flex';
                setTimeout(() => {
                    updateChart();
                    document.getElementById('chartLoading').style.display = 'none';
                }, 800);
            });

            // 滚动效果
            window.addEventListener('scroll', () => {
                const header = document.getElementById('mainHeader');
                if (window.scrollY > 20) {
                    header.classList.add('shadow-md', 'py-2');
                    header.classList.remove('shadow-sm', 'py-4');
                } else {
                    header.classList.add('shadow-sm', 'py-4');
                    header.classList.remove('shadow-md', 'py-2');
                }
            });
        });

        // 响应式调整
        window.addEventListener('resize', () => myChart.resize());
    </script>
</body>
</html>